#include"cpp-httplib/httplib.h"
#include"searcher.hpp"
#include"log.hpp"

const std::string root_path = "./wwwroot/";
const std::string input = "data/raw_html/raw.txt";

int main() {

    //初始化searcher
    ns_searcher::Searcher search;
    search.InitSearcher(input);

    httplib::Server svr;

    //设置根目录
    svr.set_base_dir(root_path.c_str());

    svr.Get("/search", [&search](const httplib::Request& req, httplib::Response& rsp) {

        //如果没有参数word(搜索关键字)
        if (!req.has_param("q")) {
            //第二个参数对应http的content-type，例如：text/html表示返回的内容是一个网页内容，希望浏览器当成网页来解释
            rsp.set_content("必须要有搜索关键字！", "text/plain; charset=utf-8");
            return ;
        }

        //取出对应参数内容，并进行搜索
        std::string word = req.get_param_value("q");
        // std::cout << "User is searching: " << word << std::endl;
        LOG(NORMAL, "User is searching: " + word);
        std::string json_string;
        search.Search(word, &json_string);

        //返回搜索结果
        rsp.set_content(json_string, "application/json");
    });

    LOG(NORMAL, "服务器启动成功...");    
    //监听端口号为8081的任意IP地址
    svr.listen("0.0.0.0", 8081);    
    return 0;
}